<template>
  <view class="branch-container">
    <view class="loading-container" v-show="loading">
      <u-loading mode="circle" show />
    </view>
    <view class="form-container">
      <u-form :model="form" ref="uForm" :rules="rules">
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="twoWordLabelStyle"
          label="省份"
          prop="province"
        >
          <u-input
            v-model="form.province"
            type="select"
            :select-open="selectionKey === 'province'"
            placeholder="请选择"
            @tap="() => handleSelectOpen('province')"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="twoWordLabelStyle"
          label="城市"
          prop="city"
        >
          <u-input
            v-model="form.city"
            type="select"
            :select-open="selectionKey === 'city'"
            placeholder="请先选择省份"
            @tap="() => handleSelectOpen('city')"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="twoWordLabelStyle"
          label="区县"
          prop="area"
        >
          <u-input
            v-model="form.area"
            type="select"
            :select-open="selectionKey === 'area'"
            placeholder="请先选择城市"
            @tap="() => handleSelectOpen('area')"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="commonLableStyle"
          label="街道"
          prop="street"
        >
          <u-input v-model="form.street" placeholder="请输入街道" />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="twoWordLabelStyle"
          label="品牌"
          prop="brand"
        >
          <u-input
            v-model="form.brand"
            type="select"
            :select-open="selectionKey === 'brand'"
            placeholder="请选择"
            @tap="() => handleSelectOpen('brand')"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="commonLableStyle"
          label="市场类型"
          prop="marketType"
        >
          <u-input
            v-model="form.marketType"
            type="select"
            :select-open="selectionKey === 'marketType'"
            placeholder="请选择"
            @tap="() => handleSelectOpen('marketType')"
          />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="commonLableStyle"
          label="市场名称"
          prop="marketName"
        >
          <u-input v-model="form.marketName" placeholder="请输入建材市场名称" />
        </u-form-item>
        <u-form-item
          :border-bottom="false"
          label-width="150rpx"
          :label-style="commonLableStyle"
          label="详细地址"
          prop="marketAddress"
        >
          <u-input v-model="form.marketAddress" placeholder="请输入市场详细地址" />
        </u-form-item>
      </u-form>
    </view>
    <view class="footer-container">
      <u-button
        class="footer-btn"
        shape="circle"
        @click="handleSaveForm"
        type="primary"
        >保存</u-button
      >
    </view>
    <!-- 筛选弹出框 -->
    <u-picker
      mode="selector"
      class="my-u-picker"
      v-model="showSelection"
      safe-area-inset-bottom
      @confirm="handleSelectionChange"
      :range="selectionOpts"
      :z-index="9999"
      range-key="text"
    />

    <u-toast ref="uToast" />
  </view>
</template>

<script>
import {
  provinceList,
  getAllRegionByParentId,
  getBrandList,
  createBranchInvestOrder,
  getSystemDictData,
  getBranchInvestOrderDetail,
  editBranchInvestOrder,
} from "../../common/service.js";
const commonLableStyle = {
  width: "134rpx",
  paddingRight: "16rpx",
  justifyContent: "space-between",
  color: "#666",
  fontSize: "28rpx",
};
export default {
  data() {
    return {
      form: {
        province: "",
        city: "",
        area: "",
        street: "",
        brand: "",
        marketType: "",
        marketName: "",
        marketAddress: '',
      },
      selectionOptMap: {
        province: [],
        city: [],
        area: [],
        brand: [],
        marketType: [],
      },
      showSelection: false,
      selectionKey: "",
      loading: false,
      commonLableStyle,
      twoWordLabelStyle: {
        ...commonLableStyle,
        display: "grid",
        gridTemplateColumns: "1fr 1fr",
        // letterSpacing: '22rpx',
      },
      rules: {
        province: [{ required: true, message: "请选择省份" }],
        city: [{ required: true, message: "请选择城市" }],
        area: [{ required: true, message: "请选择区县" }],
        brand: [{ required: true, message: "请选择品牌" }],
        street: [{ required: true, message: "请输入街道" }],
        marketType: [{ required: true, message: "请选择市场类型" }],
        marketName: [{ required: true, message: "请输入市场名称" }],
        marketAddress: [{ required: true, message: "请输入市场详细地址" }],
      },
      orderCreator: null,
      orderId: null,
    };
  },
  watch: {
    // 当点击空白页，不会有cancel事件，所以监听model值
    showSelection(value) {
      if (value === false) {
        this.selectionKey = "";
      }
    },
  },
  computed: {
    selectionOpts() {
      if (!this.selectionKey) return [];
      return this.selectionOptMap[this.selectionKey] || [];
    },
    uid() {
      return this.CONFIG.user.id.toLowerCase();
    },
    canSave() {
      return !this.orderId || (this.orderId && this.uid === this.orderCreator)
    }
  },
  async created() {
    this.fetchMarketTypeOpts();
    await this.fetchTopologyDataByType('1', 'province');
    this.fetchBrandList();
  },
  onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
  onLoad(option) {
    const { id } = option;
    this.orderId = id;
    if (id) {
      this.fetchDetail(id);
    }
    this.move();
  },
  methods: {
    // 允许页面滚动
    move() {
      var box = function (e) {
        passive: false
      };
      document.body.style.overflow = ''; // 出现滚动条
      document.removeEventListener("touchmove", box, false);
    },
    fetchDetail(id) {
      getBranchInvestOrderDetail(id, async (result) => {
        if (!result || result.statusCode !== 200) {
          return;
        }
        const { data: rs } = result;
        if (rs.code === 200) {
          const {
            province,
            city,
            area,
            street,
            brand,
            marketType,
            marketName,
            marketAddress,
            status,
            createBy,
          } = rs.data
          if (status !== '0') {
            this.$refs.uToast.show({
              title: "当前状态不为新建，不允许修改！",
              type: "error",
              duration: 3000,
            });
          }
          this.orderCreator = createBy;
          this.form = {
            province,
            city,
            area,
            street,
            brand,
            marketType,
            marketName,
            marketAddress,
          }
          const provinceData = (this.selectionOptMap.province || []).find(p => p.text === province);
          if (provinceData) {
             const citys = await this.fetchTopologyDataByType(provinceData.value, "city");
             const cityData = citys.find(c => c.text === city);
             this.fetchTopologyDataByType(cityData.value, "area");
          }
        }
      })
    },
    handleSaveForm() {
      this.$refs.uForm.validate((valid) => {
        if (!valid) return;
        this.submitFormData(this.form);
      });
    },
    submitFormData(params) {
      this.loading = true;
      const submitMethod = this.orderId ? editBranchInvestOrder : createBranchInvestOrder;
      if (this.orderId) {
        params.id = this.orderId;
      }
      submitMethod(
        params,
        (result) => {
          this.loading = false;
          if (result && result.statusCode == 200) {
            const { data: rs } = result;
            if (rs.code == 200) {
              this.$refs.uToast.show({
                title: "操作成功，正在跳转",
                type: "success",
                duration: 1000,
                callback: function () {
                  uni.navigateBack({
                    delta: 1, // 返回上一个页面
                  });
                }
              });
              
            } else {
              this.$refs.uToast.show({
                title: rs.msg,
                type: "error",
                duration: 3000,
              });
            }
          }
        },
        () => {
          this.loading = false;
        }
      );
    },
    handleSelectionChange(e) {
      const index = e[0];
      const currentPickType = this.selectionKey;
      const opts = this.selectionOpts;
      if (!opts || !opts.length) return;
      const { text: value, value: id } = opts[index];
      const oldValue = this.form[currentPickType];
      if (value === oldValue) return;
      switch (currentPickType) {
        case "province":
          this.form = {
            ...this.form,
            province: value,
            city: "",
            area: "",
          };
          this.fetchTopologyDataByType(id, "city");
          setTimeout(() => {
            this.handleSelectOpen('city');
          }, 500);
          break;
        case "city":
          this.form = {
            ...this.form,
            city: value,
            area: "",
          };
          this.fetchTopologyDataByType(id, "area");
          setTimeout(() => {
            this.handleSelectOpen('area');
          }, 500);
        default:
          this.form[currentPickType] = value;
          break;
      }
    },
    handleSelectOpen(type) {
      this.selectionKey = type;
      this.showSelection = true;
    },
    // 获取省市区拓扑数据
    fetchTopologyData(parentId) {
      return new Promise((resolve, reject) => {
        getAllRegionByParentId(
          parentId,
          (result) => {
            if (result && result.statusCode == 200) {
              const { data: rs } = result;
              if (rs.code == 200) {
                resolve(
                  (rs.data || []).map((item) => ({
                    text: item.regionName,
                    value: item.id,
                  }))
                );
              } else {
                this.$refs.uToast.show({
                  title: rs.msg || rs.errMsg || "获取省市区数据失败",
                  type: "error",
                  duration: 3000,
                });
                reject(rs.msg);
              }
            }
          },
          (e) => {
            this.$refs.uToast.show({
              title: e || "获取省市区数据失败",
              type: "error",
              duration: 3000,
            });
            reject(e);
          }
        );
      });
    },
    async fetchTopologyDataByType(parentId = '1', selectionType) {
      const data = await this.fetchTopologyData(parentId);
      this.selectionOptMap[selectionType] = data;
      return data;
    },
    fetchMarketTypeOpts() {
      getSystemDictData("MARTET_TYPE", (result) => {
        if (result && result.statusCode == 200) {
            const { data: rs } = result;
            if (rs.code == 200) {
              this.selectionOptMap.marketType = (rs.data || []).map((item) => ({
                text: item.dictLabel,
                value: item.dictLabel,
              }));
            } else {
              this.$refs.uToast.show({
                title: rs.msg || rs.errMsg || "获取市场类型失败",
                type: "error",
                duration: 3000,
              });
            }
          }
      });
    },
    fetchBrandList() {
      getBrandList(
        {},
        (result) => {
          if (result && result.statusCode == 200) {
            const { data: rs } = result;
            if (rs.code == 200) {
              this.selectionOptMap.brand = (rs.brand || []).map((item) => ({
                text: item.brand,
                value: item.brandCode,
              }));
            } else {
              this.$refs.uToast.show({
                title: rs.msg || rs.errMsg || "获取品牌数据失败",
                type: "error",
                duration: 3000,
              });
            }
          }
        },
        (error) => {
          this.$refs.uToast.show({
            title: "获取品牌数据失败",
            type: "error",
            duration: 3000,
          });
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
uni-page-body {
  min-height: 100%;
  background: #f3f5f7;
}
.branch-container {
  background: #f3f5f7;
  margin-top: 20rpx;
  padding-bottom: 128rpx;
}

.form-container {
  background: #fff;
  padding: 0 30rpx;
}
/deep/ .u-form-item--right {
  background: #f7f7f7;
  padding: 14rpx 18rpx;
  border-radius: 16rpx;
}

.footer-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15rpx 25rpx 30rpx 30rpx;
  background: #fff;
}
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  z-index: 2;
  opacity: 0.8;
}
</style>
